# If running on devices without essential libraries, uncomment the next line:
# !pip install -U poly2graph sympy networkx matplotlib
import sympy as sp
import numpy as np
np.set_printoptions(threshold=20)
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import networkx as nx
# Poly2Graph (must be installed in your environment)
# If this import fails, run the pip command above.
import poly2graph as p2gSpectral Graphs & Poly2Graph — A Hands‑On Tutorial
1 Learning objectives
By the end of this tutorial, you will be able to:
- Explain what a spectral graph is (a graph traced by the energy spectrum of a 1‑D crystal on the complex plane under open boundaries).
- Understand the key mathematical objects that appear in modern treatments: the characteristic polynomial \(P(z,E)\), the spectral potential \(\Phi(E)\), and the density of states \(\rho(E)\).
- Describe prior pain points (manual inspection, numerical bottlenecks, fragile extraction) and the need for an automated tool.
- Use Poly2Graph to go from a symbolic Hamiltonian/characteristic polynomial to its spectral graph, and analyze/visualize the result.
2 What is a spectral graph (and why is it interesting)?
Basic idea :
Consider a simple 1‑D crystal (a line of repeating “cells”). Its energy levels \(E\) depend on a wavelike parameter \(k\) (momentum). A 1‑D non‑Hermitian system is a tight‑binding chain whose effective Hamiltonian \(H\) is not equal to its adjoint (\(H \neq H^{\dagger}\)), e.g., due to asymmetric couplings, gain/loss, or non‑reciprocal driving. Consequently, eigenenergies are generally complex (\(E \in \mathbb{C}\)) and right/left eigenvectors differ (biorthogonality).
In such one‑dimensional non‑Hermitian systems with a point gap, under periodic boundaries (“a loop”), energies trace closed loops as \(k\) runs from \(0\) to \(2\pi\).
Under open boundaries (“a finite chain”), something shocking can happen in non‑Hermitian systems (with loss/gain or non‑reciprocal couplings): the eigen‑energies collapse into arcs and loops assembled into a planar spectral graph embedded in the complex plane. Geometrically, OBC energies lie on intersection lines of inverse‑skin‑depth surfaces \(\mathrm{Im}\,k=-\log|z|\) defined by \(P(z,E)=0\): the intersection of two such surfaces produces an edge, and the intersection of three or more surfaces produces a vertex. To simply put, connect those arcs/loops and you get a spectral graph.
Algebraic formulation:
Let \(H(z)\) be the Bloch Hamiltonian with \(z=e^{ik}\) and \[ P(z,E)=\det\!\big[H(z)-EI\big]=\sum_{n=-p}^{q} a_n(E)\,z^n . \] For a fixed \(E\), order the \(z\)‑roots of \(P(z,E)=0\) by magnitude \(|\beta_1(E)|\le\cdots\le|\beta_{p+q}(E)|\). The generalized Brillouin zone (GBZ) is characterized by the equality \[ |\beta_p(E)|=|\beta_{p+1}(E)|, \] and the corresponding loci of \(E\) form the OBC spectral graph. In particular, the density of states (DOS) in the continuum limit is supported only along these loci (as a singular distribution along curves, rather than an area region). In multi‑band systems there may also exist isolated edge modes outside the continuum spectral graph.
Potential‑theoretic view:
A convenient “spectral potential” (Ronkin function) can be defined from the \(z\)‑roots; one common choice (up to an additive constant and a sign convention) is \[ \Phi(E)=-\log|a_q(E)|-\sum_{i=p+1}^{p+q}\log|\beta_i(E)|. \] Its Laplacian yields the density of states(DOS), \[ \rho(E)=-\frac{1}{2\pi}\,\nabla^2\Phi(E), \] where the sign depends on the convention used for \(\Phi\). In the distributional sense, \(\rho(E)\) has support only on the spectral graph. Equivalently, the spectral graph coincides with the ridges/troughs of \(\Phi(E)\) (depending on the sign convention).
Intuition: treat each eigenvalue \(\epsilon_n\) as a tiny electric charge \(\rho(E) = \lim_{N\to\infty}\sum_n \frac{1}{N} \delta(E-\epsilon_n)\); while \(\Phi(E)\) is an electrostatic‑like potential whose “ridges/troughs” trace the spectral graph; \(\rho(E)\) is nonzero only on the graph. Please see the Section 8 below for a concrete illustration.
Why interesting?
Within Non‑Hermitian systems:
Non-Hermitian spectra can realize many more graph connectivities than standard topological labels (like \(\mathbb{Z},\mathbb{Z}_2\)): stars, flowers, braids, etc., with novel transitions that change the number of endpoints/junctions/loops (no Hermitian analog). This is naturally expressed by writing dispersions as bivariate Laurent polynomials \(P(E,z)\) and studying how their imaginary‑momentum (“inverse skin depth”) surfaces intersect across the \(E\)‑plane.
Beyond Hamiltonians (algebra‑to‑graph):
Spectral graph is a general algebra-to-graph bridge. Because the equation \(\Phi(E) = - \log|a_q(E)| - \sum_{i=p+1}^{p+q}\log|\beta_i(E)|\) uses only \(P(E,z)\), the construction extends to arbitrary Laurent polynomials, and via standard reductions to vectors and matrices. You get a universal topological fingerprint for many algebraic objects—making graph learning a front-door to problems in linear algebra, signal processing, photonics, circuits, and more.
Automation usage:
The Poly2Graph pipeline automates the construction above: it evaluates \(z\)‑roots via Frobenius companion eigen‑solvers with automatic backend detection (and optional GPU/TPU acceleration when TensorFlow or PyTorch is available), builds \(\Phi(E)\) and \(\rho(E)\) on an adaptive grid, and extracts a one‑pixel‑wide skeleton via morphological thinning to obtain a NetworkX MultiGraph with full edge geometry. In rare low‑DOS or long‑range multi‑band settings, local numerical instabilities can arise; Poly2Graph mitigates them with node‑merging and short‑edge contraction.
Example. Here, we visualize a single-band example by an interactive 3D surface plot of \(\Phi(E)\) along with the extracted skeleton Figure 1.
3 What was hard before (and why we need Poly2Graph)?
Prior to Poly2Graph, extracting spectral graphs was manual and fragile:
- You had to scan parameters, plot large finite‑chain spectra, and visually infer the continuum graph.
- Computing the GBZ roots \(\beta_i(E)\) for every sampled energy \(E\) is a bottleneck; naive solvers are slow and memory‑hungry.
- Even with a DOS image, turning that into a clean graph with correct endpoints, junctions, and loops requires careful morphology (thresholding, skeletonization, node/edge parsing).
Poly2Graph lifts these barriers with an end‑to‑end, high‑performance pipeline:
- Accepts either \(H(z)\) (as a
sympy.Matrix) or \(P(z,E)\) (string orsympy.Poly).
- Computes the spectral potential \(\Phi(E)\) from \(z\)‑roots (fast eigen‑solvers on Frobenius companion matrices; optional GPU/TPU via TensorFlow/PyTorch).
- Takes the Laplacian to get DOS, then does adaptive, two‑stage refinement (coarse mask → high‑res on just ~1–5% of the region).
- Applies image morphology to extract a one‑pixel skeleton, then returns a NetworkX MultiGraph with full edge geometry (the sampled curve).
This automation has enabled HSG‑12M (11.6M static + 5.1M temporal spectral multigraphs), demonstrating scale and diversity previously out of reach(Learn more from @arXiv:2506.08618 if interested).
Now let’s try to use Poly2Graph
# For better plotly rendering in Jupyter environments
import plotly.io as pio
pio.renderers.default = "plotly_mimetype+notebook_connected"Please ensure your version of Python >= 3.11 , you can check the installation:
print("Poly2Graph version:", p2g.__version__)Poly2Graph version: 0.2.0
# Always remember to define common symbols first
k = sp.symbols('k', real=True)
z, E = sp.symbols('z E', complex=True)4 1. A quick start: One‑band example
We’ll start from a simple one‑band characteristic polynomial and obtain its spectral graph.
Characteristic polynomial $ P(z,E) = z^4 - z^2 - z^{-1} - E $ (This corresponds to a scalar Bloch Hamiltonian \(h(z)=z^4-z^2-z^{-1}\), with \(z=e^{ik}\).)
The valid input formats to initialize a p2g.SpectralGraph object are: 1. Characteristic polynomial in terms of z and E: - as a string of the Poly in terms of z and E - as a sympy’s Poly (sympy.polys.polytools.Poly) with {z, 1/z, E} as generators 2. Bloch Hamiltonian in terms of k or z - as a sympy Matrix in terms of k - as a sympy Matrix in terms of z
All the following characteristics are valid and will initialize to the same characteristic polynomial and therefore produce the same spectral graph
char_poly_str = '-z**-1 - E - z**2 + z**4'
char_poly_Poly = sp.Poly(
-z**-1 - E - z**2 + z**4,
z, 1/z, E # generators are z, 1/z, E
)
phase_k = sp.exp(sp.I*k)
char_hamil_k = sp.Matrix([-phase_k**-1 - phase_k**2 + phase_k**4])
char_hamil_z = sp.Matrix([-z**-1 - E - z**2 + z**4])Here we use the string format as the initialization example.
sg = p2g.SpectralGraph(char_poly_str, k=k, z=z, E=E)# print the number of energy bands
print('Bands:', sg.num_bands)
# print the max hopping range (p,q)
print('Max hop (right):', sg.poly_p, 'Max hop (left):', sg.poly_q)
# print the [Ereal_min,Ereal_max,Eimag_min,Eimag_max] window
print('Spectral window (auto-estimated):', sg.spectral_square) Bands: 1
Max hop (right): 1 Max hop (left): 4
Spectral window (auto-estimated): [-2.31139048 1.6398687 -1.97562959 1.97562959]
We will see Poly2Graph automatically compute set of properties next:
sg.ChP\(\displaystyle \operatorname{Poly}{\left( z^{4} - z^{2} - \frac{1}{z} - E, z, \frac{1}{z}, E, domain=\mathbb{Z} \right)}\)
Bloch Hamiltonian:
- For one-band model(The exponent of \(E\) is 1), it is a unique, rank-0 matrix (scalar)
sg.h_k\(\displaystyle \left[\begin{matrix}e^{4 i k} - e^{2 i k} - e^{- i k}\end{matrix}\right]\)
or in \(z\) format(recall that \(z = e^{ik}\))
sg.h_z\(\displaystyle \left[\begin{matrix}- \frac{- z^{5} + z^{3} + 1}{z}\end{matrix}\right]\)
Frobenius Companion Matrix of \(P(z, E)\):
- The Frobenius companion matrix is a special matrix whose eigenvalues are exactly the roots of the characteristic polynomial \(P(z, E)\) for fixed \(E\).
- In
Poly2Graph,sg.companion_Egives this matrix (with \(E\) as a parameter, \(z\) as variable). - Purpose:
- Efficiently computes all \(z\)-roots for any \(E\) using linear algebra (eigenvalues), instead of slow root-finding.
- These \(z\)-roots are essential for calculating the spectral graph, GBZ, spectral potential, and density of states.
sg.companion_E\(\displaystyle \left[\begin{matrix}0 & 0 & 0 & 0 & 1\\1 & 0 & 0 & 0 & E\\0 & 1 & 0 & 0 & 0\\0 & 0 & 1 & 0 & 1\\0 & 0 & 0 & 1 & 0\end{matrix}\right]\)
It is a key tool for automating and accelerating spectral graph extraction in Poly2Graph.
4.1 Spectral potential \(\Phi(E)\), density of states \(\rho(E)\), and skeleton
We compute \(\Phi(E)\) and \(\rho(E)\) on a grid of complex energies, then binarize \(\rho(E)\) to get a skeleton.
::: {#cell-1 band spectral images .cell execution_count=12}
phi, dos, skel = sg.spectral_images()
fig, axes = plt.subplots(1, 3, figsize=(8, 3), sharex=True, sharey=True)
# 1) Spectral potential
axes[0].imshow(phi, extent=sg.spectral_square, origin='lower', cmap='terrain')
axes[0].set(xlabel='Re(E)', ylabel='Im(E)', title='Spectral Potential')
# 2) Density of States
pmin, pmax = np.percentile(dos, (0.1, 99.9))
# Clip extreme DOS to increase visibility
norm = colors.Normalize(vmin=pmin, vmax=pmax)
axes[1].imshow(dos, extent=sg.spectral_square, cmap='viridis', norm=norm)
axes[1].set(xlabel='Re(E)', title='Density of States')
# 3) Binarized skeleton
axes[2].imshow(skel, extent=sg.spectral_square, cmap='gray')
axes[2].set(xlabel='Re(E)', title='Graph Skeleton')
plt.tight_layout()
plt.savefig("assets/1-band-example_si.png")
plt.show()
:::
4.2 Extract the spectral graph
Next, we visualize these results by a interactive 3D surface plot of \(\Phi(E)\) along with the extracted skeleton.
import plotly.graph_objects as go
E_re = np.linspace(*sg.spectral_square[:2], phi.shape[0])
E_im = np.linspace(*sg.spectral_square[2:], phi.shape[1])
fig = go.Figure(data=[go.Surface(z=phi, x=E_re, y=E_im,
opacity=0.6, colorscale='Spectral_r')])
fig.update_layout(
scene=dict(
aspectratio=dict(x=1.5, y=1, z=.8),
xaxis_title='Re(E)',yaxis_title='Im(E)',zaxis_title='Phi(E)',
),
title='3D Surface Plot of Spectral Potential',
width=700, height=600
)
fig.show()